<?php

namespace app\admin\controller\autokeyword;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 生效表管理
 * @icon fa fa-circle-o
 */
class Table extends Backend
{

    /**
     * AutokeywordTable模型对象
     * @var \app\admin\model\AutokeywordTable
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AutokeywordTable;
        $this->view->assign("markList", $this->model->getMarkList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $params['action'] = trim(implode(',', $params['action']), ',');

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $tableList = $this->getTableList();
        $fieldList = $this->getTableField($tableList[0]['name']);

        $this->view->assign('tableList', $tableList);
        $this->view->assign('fieldList', $fieldList->getData());

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $tableList = $this->getTableList();
        $fieldList = $this->getTableField($row['table']);

        $this->view->assign('tableList', $tableList);
        $this->view->assign('fieldList', $fieldList->getData());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $params['action'] = trim(implode(',', $params['action']), ',');

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /**
     * 获取数据库表
     * @return mixed
     * @throws PDOException
     */
    private function getTableList()
    {
        $dbName = \think\Config::get('database.database');

        $sql = "SELECT TABLE_NAME AS name, TABLE_COMMENT as comments FROM information_schema.tables WHERE table_schema = '{$dbName}';";

        try {
            $list = Db::query($sql);
        } catch (PDOException $exception) {
            throw $exception;
        }

        return $list;
    }

    /**
     * 获取数据库表的字段
     *
     * @param string|null $tableName
     *
     * @return \think\response\Json
     * @throws PDOException
     */
    public function getTableField(string $tableName = null)
    {
        $this->request->filter(['strip_tags', 'trim']);


        if (is_null($tableName)) {
            $tableName = $this->request->request('tableName');
            if (!is_null($tableName)) {
                $this->error('该页面不存在');
            }
        }

        $dbName = \think\Config::get('database.database');

        $sql = "SELECT COLUMN_NAME AS name, COLUMN_COMMENT AS comments FROM information_schema.columns WHERE table_schema = '{$dbName}' AND table_name = '{$tableName}' ORDER BY ORDINAL_POSITION ASC";

        try {
            $list = Db::query($sql);
        } catch (PDOException $exception) {
            throw $exception;
        }

        $actionList = $this->getModelAction($tableName);

        $data['field'] = $list;
        $data['action'] = [];

        if ($actionList) {
            $data['action'] = $actionList;
        }

        return json($data);

    }

    /**
     * 获取对应控制的方法
     * @param string $tableName
     *
     * @return bool|\ReflectionMethod[]
     */
    private function getModelAction(string $tableName)
    {
        $className = $this->getClassName($tableName);

        try {
            $rc     = new \ReflectionClass($className);
            $action = $rc->getMethods(\ReflectionMethod::IS_PUBLIC);

        } catch (\ReflectionException $e) {
            if ($e->getCode() === -1) {
                return false;
            }
        }

        return $action;
    }

    /**
     * 获取对应类名
     *
     * @param string      $tableName
     * @param string|null $rootPath
     * @param null        $nameSpace
     * @param bool        $off
     *
     * @return bool
     */
    private function getClassName(string $tableName, string $rootPath = null, $nameSpace = null)
    {
        // 拆分表名
        $modelNameAll = explode('_', $tableName);
        // 去除表前缀
        array_shift($modelNameAll);
        // 末尾数组值出栈（表名）
        $tableNameLast = array_pop($modelNameAll);
        // 首字母大写（第一种名称情况）
        $modelName[] = ucwords($tableNameLast).'.php';

        // 大于0时获取第二种第三种名称情况
        if (count($modelNameAll) > 0) {
            $modelNameA = '';

            foreach ($modelNameAll as $value) {
                $modelNameA .= $value;
            }

            $modelName[] = ucwords($modelNameA).'.php';
        }

        // 控制器路径
        if (!$rootPath) {
            $rootPath = ROOT_PATH . 'application' . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'controller'. DIRECTORY_SEPARATOR;
            $nameSpace = 'app\admin\controller';
        }

        // 读取目录内容
        $dir = scandir($rootPath);

        // 遍历查找
        foreach ($dir as $value) {
            if ($value == '.' || $value == '..') {
                continue;
            }
            // 判断是否是文件
            if(is_file($rootPath.$value)) {

                // 判断文件是否是需要的
                if (in_array($value, $modelName, true)) {
                    $value = explode('.', $value);
//
                    // 返回完整类命名空间地址
                    return $nameSpace.'\\'.array_shift($value);
                    break;
                }
            };

            if (is_dir($rootPath . $value)) {
                $isFile = $this->getClassName($tableName, $rootPath.$value.DIRECTORY_SEPARATOR, $nameSpace.'\\'.$value, true);

                if ($isFile) {
                    return $isFile;
                    break;
                }
                continue;

            };
        }

        return false;

    }
}
